#coding=utf-8
from uliweb import expose, decorators

def get_systems_list_view(c):
    from uliweb.utils.generic import ListView
    from uliweb.orm import get_model
    from uliweb import request
    from uliweb.core.html import Tag
    from sqlalchemy.sql import or_
    
    def name(value, obj):
        return str(Tag('a', value, href="/systems/%s" % obj.id))
    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page=int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
    System = get_model('system')
    condition = None
    query = None
#    if request.user.is_superuser:
#        pass
#    elif request.user.is_gm:
#        if request.user.kfzx:
#            query = request.user.kfzx.kfzx_systems()
#    else:
    #如果用户是条线或开发中心，则可以查看所有系统
#    if not request.department in ('1', '3'):
#        query = request.user.users_systems.all()

    if c.get('sys_name'):
        condition = or_(System.c.sys_id.like('%' + c['sys_name'] + '%'),
            System.c.name.like('%' + c['sys_name'] + '%'),
            System.c.abbr.like('%' + c['sys_name'] + '%'),
            ) & condition
    if c.get('kfzx'):
        condition = (System.c.kfzx == c['kfzx']) & condition
    if c.get('sys_type'):
        condition = (System.c.sys_type == c['sys_type']) & condition
    
            
    fields_convert_map = {'name':name}
    view =  ListView(System, condition=condition, query=query, pageno=pageno, 
        rows_per_page=rows_per_page, fields_convert_map=fields_convert_map)
        
    return view

@decorators.require_login
@expose('/systems')
def systems_list():
    from query import create_system_query
    
    query = create_system_query(url_for(systems_list))
    condition = query.run()

    view = get_systems_list_view(condition)
    if 'download' in request.values:
        return view.download('systems.xls', action='download', timeout=0)
    elif 'data' in request.values:
#        result = view.run(head=False, body=True)
#        return json(result)
        return json(view.json())
    else:
        result = view.run(head=True, body=False)
        result.update({'query_form':query.form, 'table':view})
        return result
    
@decorators.require_login
@expose('/systems/add')
def systems_add():
    if request.user.is_superuser:
        from uliweb.utils.generic import AddView
        
        view = AddView('system', url_for(systems_list))
        return view.run()
    else:
        flash('你不是超级用户，无法添加新系统！')
        return redirect(url_for(systems_list))
    
@decorators.require_login
@expose('/systems/<id>')
def systems_view(id):
    from uliweb.utils.generic import DetailView
    import uliweb.orm as orm
    from uliweb.utils.textconvert import text2html
    
    System = orm.get_model('system')
    condition = (System.c.id == int(id))
    def selfdev_if(value, obj):
        if obj.selfdev_if:
            selfdev_if = u'是'
        else:
            selfdev_if = u'否'
        return "<span id='selfdev_if'>%s</span>" % selfdev_if
    
    view = DetailView('system', condition=condition, template_data={'tab_id':request.values.get('tab', 0)})
    view.fields_convert_map = {'reason':text2html, 'selfdev_if':selfdev_if}
    return view.run()
    
@decorators.require_login
@expose('/systems/<id>/edit')
def systems_edit(id):
    from uliweb.utils.generic import EditView
    from uliweb.form import TextField
    from uliweb import orm, request
    
    System = orm.get_model('system')
    Selfdev = orm.get_model('selfdev')
    obj = System.get(System.c.id == int(id))
    
    def post_created_form(fcls, model, obj):
        fcls.users.condition = None
        if not request.user.is_superuser:
            a = list(request.user.members.all().values('id', 'username'))
            b = list(obj.users.all().values('id', 'username'))
            d = [(x, y) for x, y in a + b]
            fcls.users.choices = sorted(set(d))
        
    def pre_save(obj, data):
        data['users'].append(obj._manager_)
        
    def post_save(obj, data):
        self = Selfdev.get(Selfdev.c.system==obj.id)
        if self:
            self.kfzx = obj._kfzx_
            self.save()
    
    if request.user.is_superuser or obj._manager_ == request.user.id:
        if request.user.is_superuser:
            fields = ('sys_id', 'name', 'abbr', 'stage', 'transfer_date', 
            'reason', 'kfzx', 'sys_type', 'rate', 'construction', 'contact', 'memo', 'manager', 'users', 'observers')
        else:
            fields = ('name', 'abbr', 'stage', 'transfer_date', 'reason', 'rate', 'construction', 'contact', 'memo', 'users', 'observers')
        view = EditView('system', ok_url=url_for(systems_view, id=int(id)), obj=obj,
            post_created_form=post_created_form, fields=fields, pre_save=pre_save,
            post_save=post_save)
        view.builds_args_map = {TextField:{'rows':10}}
        return view.run()
    else:
        flash('你不是超级用户或管理员，无法编辑此系统！')
        return redirect(url_for(systems_list))
    
@decorators.require_login
@expose('/systems/<id>/delete')
def systems_delete(id):
    from uliweb.utils.generic import DeleteView
    from uliweb import orm
    
    System = orm.get_model('system')
    obj = System.get(System.c.id == int(id))
    
    if request.user.is_superuser:
        view = DeleteView('system', ok_url=url_for(systems_list), obj=obj)
        return view.run()
    else:
        flash('你不是超级用户，无法删除此系统！')
        return redirect(url_for(systems_list))
    
@decorators.require_login
@expose('/systems/<id>/details_add')
def systems_details_add(id):
    """
    明细信息
    """ 
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from uliweb.form import DateField
    from plugs.ui.jquery.jquery.widgets import DatePicker
    from datetime import datetime
    from uliweb.form.template_layout import TemplateLayout
    import generic.views as g_views
      
    get_url = g_views.get_url('/systems/%s' % id)
        
    System = get_model('system')
    sys = System.get(System.c.id == int(id))
    
    data = {}
    data['system'] = sys.get_display_value('name')
    data['kfzx'] = sys.kfzx.name
    data['detail_time'] = datetime.now()
    
    detail_time = DateField('当月时间', required=True, build=DatePicker, help_string='可为填报月的任意一天')
    
    static_fields = ('system', 'kfzx')
    fields = ('system', 'kfzx', 'inner_number', 'outter_number', ('detail_time',detail_time))
    
    def post_created_form(fcls, model):
        fcls.layout_class = TemplateLayout
        fcls.layout = 'layout_systems_details.html'
    
    def pre_save(data):
        data.update(sys.to_dict(fields=static_fields, convert=False))
        data['system'] = sys
        data['kfzx'] = sys.kfzx
        data['year'] = data['detail_time'].year
        data['month'] = data['detail_time'].month
        data['year_month'] = data['year']*100 + data['month']

    view = AddView('resource', ok_url='/systems/%s' % id, fields=fields, 
        static_fields=static_fields, data=data, pre_save=pre_save, 
        post_created_form=post_created_form)
        
    return g_views.generic_add(get_url=get_url, layout='systems_layout.html', 
            title='填报当月资源投入', view=view, template='systems_details_add.html')

@decorators.require_login
@expose('/systems/<id>/details')
def systems_details(id):
    from uliweb.orm import get_model
    
    System = get_model('system')
    obj = System.get(int(id))
    Resource = get_model('resource')
    
    objs = Resource.filter(Resource.c.system == int(id)).order_by(Resource.c.year_month.desc())

    return {'objects':objs}

@decorators.require_login
@expose('/systems/details/<id>/delete')
def systems_details_delete(id):
    from uliweb.utils.generic import DeleteView
    from uliweb.orm import get_model
    
    Resource = get_model('resource')
    obj = Resource.get(Resource.c.id == int(id))
    
    view = DeleteView('resource', ok_url='/systems/%s' % obj.system.id, obj=obj)
    return view.run()

@decorators.require_login
@expose('/systems/details/<id>/edit')
def systems_details_edit(id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from uliweb.form import DateField
    from plugs.ui.jquery.jquery.widgets import DatePicker
    from datetime import datetime
    from uliweb.form.template_layout import TemplateLayout
    
    
    Resource = get_model('resource')
    obj = Resource.get(Resource.c.id == int(id))
    
    old_data = obj.to_dict()
    
    data = {}
    data['system'] = obj.system.name
    data['kfzx'] = obj.kfzx.name
    data['detail_time'] = datetime(obj.year_month/100, obj.year_month%100, 1)
    
    detail_time = DateField('当月时间', required=True, build=DatePicker, help_string='可为填报月的任意一天')
        
    static_fields = ('system', 'kfzx')
    fields = ('system', 'kfzx', 'inner_number', 'outter_number', ('detail_time',detail_time))
    
    def post_created_form(fcls, model, obj):
        fcls.layout_class = TemplateLayout
        fcls.layout = 'layout_systems_details_edit.html'
        
    def pre_save(obj, data):
        for k in static_fields:
            del data[k]
        data['system'] = obj.system
        data['kfzx'] = obj.kfzx  
        data['year'] = data['detail_time'].year
        data['month'] = data['detail_time'].month
        data['year_month'] = data['year']*100 + data['month']
        data['modified_user'] = request.user.id
    
        
    view = EditView('resource', ok_url='/systems/%s' % obj.system.id, obj=obj, data=data,
        post_created_form=post_created_form, fields=fields, 
        static_fields=static_fields, pre_save=pre_save)
    return view.run()
    
@decorators.require_login
@expose('/systems/query')
def systems_query():
    from uliweb.orm import get_model
    from sqlalchemy.sql import or_
    
    System = get_model('system')
    result = []
    condition = ~(System.c.sys_type.in_(['5']))
    if 'user' in request.values:
        if request.user.is_superuser:
            pass
        elif request.user.is_gm:
            if request.user._kfzx_:
                condition = (System.c.kfzx == request.user._kfzx_) & condition
            else:
                pass
        else:
            condition = (System.users.in_(request.user.id) | (System.c.manager == request.user.id)) & condition 
      
    if 'term' in request.values:
        term = request.values['term']
        condition = or_(System.c.name.like('%'+term+'%'),
            System.c.abbr.like('%'+term+'%'),
            System.c.sys_id.like('%'+term+'%')) & condition
    query = System.filter(condition).order_by(System.c.sys_id)
    for row in query:
        result.append([row.id, unicode(row)])
    return json(result)
    
    
    
    
    

   


